<template>
  <el-cascader
    ref="AreaCasscader"
    :options="options"
    :props="props"
    :class="customClass"
    v-model="selectRegion"
    @change="getSelectInfo"
     filterable
    clearable></el-cascader>
</template>

<script>
import system from '@/api/system'
export default {
  name: 'AreaCascader',
  props: {
    customClass: {type: String, default: ''},
    province: String,
    provinceCode: {type: [String, Number], default: ''},
    city: String,
    cityCode: {type: [String, Number], default: ''},
    area: String,
    areaCode: {type: [String, Number], default: ''}
  },
  mounted () {
    this.getAreaInfoList()
  },
  data () {
    return {
      props: {
        multiple: false,
        value: 'code',
        label: 'name',
        expandTrigger: 'click'
      },
      selectRegion: [this.provinceCode, this.cityCode, this.areaCode],
      regionProvince: this.province,
      regionProvinceCode: this.provinceCode,
      regionCity: this.city,
      regionCityCode: this.cityCode,
      regionArea: this.area,
      regionAreaCode: this.areaCode,
      options: []
    }
  },
  watch: {
    regionProvince (val) {
      this.$emit('update:province', val)
    },
    regionProvinceCode (val) {
      this.$emit('update:provinceCode', val)
    },
    regionCity (val) {
      this.$emit('update:city', val)
    },
    regionCityCode (val) {
      this.$emit('update:cityCode', val)
    },
    regionArea (val) {
      this.$emit('update:area', val)
    },
    regionAreaCode (val) {
      this.$emit('update:areaCode', val)
    }
  },
  methods: {
    getAreaInfoList () {
      system.getRegionProvinceInfoListAPI().then(res => {
        this.options = res.data
      })
    },
    getCascaderObj (val, opt) {
      return val.map((value, index, array) => {
        for (let itm of opt) {
          if (itm.code === value) {
            opt = itm.children
            return itm
          }
        }
        return null
      })
    },
    getSelectInfo (values) {
      this.selectRegion = values
      if (values && values.length > 0) {
        const region = this.getCascaderObj(values, this.options)
        this.regionProvince = region[0].name
        this.regionProvinceCode = region[0].code
        this.regionCity = region[1].name
        this.regionCityCode = region[1].code
        this.regionArea = region[2].name
        this.regionAreaCode = region[2].code
      } else {
        this.regionProvince = ''
        this.regionProvinceCode = ''
        this.regionCity = ''
        this.regionCityCode = ''
        this.regionArea = ''
        this.regionAreaCode = ''
      }
    }
  }
}
</script>

<style scoped>

</style>
